package cn.wuxing.mediation.framework.web.service;

import javax.annotation.Resource;

import java.lang.reflect.Type;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.framework.manager.*;
import com.alibaba.nacos.shaded.com.google.common.reflect.TypeToken;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGettokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiRpcOauth2GetuserinfoBycodeJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiRpcOauth2GetuserinfoBycodeJsonResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentGetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import cn.wuxing.mediation.common.constant.CacheConstants;
import cn.wuxing.mediation.common.constant.Constants;
import cn.wuxing.mediation.common.constant.UserConstants;
import cn.wuxing.mediation.common.core.domain.entity.SysUser;
import cn.wuxing.mediation.common.core.domain.model.LoginUser;
import cn.wuxing.mediation.common.core.redis.RedisCache;
import cn.wuxing.mediation.common.exception.ServiceException;
import cn.wuxing.mediation.common.exception.user.BlackListException;
import cn.wuxing.mediation.common.exception.user.CaptchaException;
import cn.wuxing.mediation.common.exception.user.CaptchaExpireException;
import cn.wuxing.mediation.common.exception.user.UserNotExistsException;
import cn.wuxing.mediation.common.exception.user.UserPasswordNotMatchException;
import cn.wuxing.mediation.common.utils.DateUtils;
import cn.wuxing.mediation.common.utils.MessageUtils;
import cn.wuxing.mediation.common.utils.StringUtils;
import cn.wuxing.mediation.common.utils.ip.IpUtils;
import cn.wuxing.mediation.framework.manager.factory.AsyncFactory;
import cn.wuxing.mediation.framework.security.context.AuthenticationContextHolder;
import cn.wuxing.mediation.system.service.ISysConfigService;
import cn.wuxing.mediation.system.service.ISysUserService;

/**
 * 登录校验方法
 *
 * @author mediation
 */
@Slf4j
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 登录验证
     *
     * @param code
     * @return 结果
     */
    public String ssmlogin(String code) {
        // 用户验证
        Authentication authentication = null;
        // 使用 code 进行钉钉登录逻辑，获取用户信息
        String employeeCode = getUserInfoFromDingTalk(code);
        if (StringUtils.isEmpty(employeeCode)) {
            log.error("【短信登陆】- 获取用户信息异常");
            throw new ServiceException("【短信登陆】登录异常");
        }
        SysUser user = userService.selectUserByEmployee(employeeCode);
//        SysUser user = userService.selectUserByPhoneNumber(phone);

        log.info("===============扫码成功后获取的用户信息:{}", JSONUtil.toJsonStr(user));
        // 创建 UserDetails，并设置权限
        UserDetails userDetails = new CustomUserDetailsService(userService, permissionService).createLoginUser(user);

        authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 登录验证
     *
     * @param code
     * @return 结果
     */
    public String zzdlogin(String code) {
        // 用户验证
        Authentication authentication = null;
        // 使用 code 进行钉钉登录逻辑，获取用户信息
        String employeeCode = getUserInfoFromDingTalk(code);
        if (StringUtils.isEmpty(employeeCode)) {
            log.error("【浙政钉】- 获取用户信息异常");
            throw new ServiceException("【浙政钉】扫码登录异常");
        }
        SysUser user = userService.selectUserByEmployee(employeeCode);
//        SysUser user = userService.selectUserByPhoneNumber(phone);

        log.info("===============扫码成功后获取的用户信息:{}", JSONUtil.toJsonStr(user));
        // 创建 UserDetails，并设置权限
        UserDetails userDetails = new CustomUserDetailsService(userService, permissionService).createLoginUser(user);

        authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    private ExecutableClient init() {
        ExecutableClient executableClient = ExecutableClient.getInstance();
        executableClient.setAccessKey(APP_KEY);
        executableClient.setSecretKey(APP_SECRET);
        executableClient.setDomainName(domainName);
        executableClient.setProtocal(PROTOCAL);
        executableClient.setTimeout(300 * 1000);
        executableClient.init();
        return executableClient;
    }

    private String getUserInfoFromDingTalk(String code) {
        ExecutableClient executableClient = init();
        String accessToken = getAccessToken(executableClient); // 获取 access_token
        ZheJiangUserInfoApiResult response = getUserInfo(accessToken, code);
        if (response == null) {
            log.error("【浙政钉】- 扫码登录获取用户信息失败");
            return null;
        }
        String employeeCode = response.employeeCode;
        return employeeCode;
    }


    public ZheJiangUserInfoApiResult getUserInfo(String accessToken, String code) {
        try {
            ExecutableClient init = init();
            IntelligentGetClient intelligentPostClient = init.newIntelligentGetClient("/rpc/oauth2/getuserinfo_bycode.json");
            OapiRpcOauth2GetuserinfoBycodeJsonRequest oapiRpcOauth2DingtalkAppUserJsonRequest = new OapiRpcOauth2GetuserinfoBycodeJsonRequest();
            //登录access_token
            oapiRpcOauth2DingtalkAppUserJsonRequest.setAccess_token(accessToken);
            //临时授权码 //回调的码
            oapiRpcOauth2DingtalkAppUserJsonRequest.setCode(code);
            log.info("【浙政钉】- 获取用户信息-请求参数：{}", JSONUtil.toJsonStr(oapiRpcOauth2DingtalkAppUserJsonRequest));
            //获取结果
            OapiRpcOauth2GetuserinfoBycodeJsonResponse apiResult = intelligentPostClient.get(oapiRpcOauth2DingtalkAppUserJsonRequest);
            log.info("【浙政钉】- 获取用户信息-响应结果：{}", JSONUtil.toJsonStr(apiResult));
            String content = apiResult.getContent();
            ZheJiangUserInfoApiResult userInfoApiResult = JSONUtil.toBean(content, ZheJiangUserInfoApiResult.class);
            return userInfoApiResult;
        } catch (Exception e) {
            log.error("【浙政钉】- 获取用户信息异常", e);
        }
        return null;
    }


    public String getAccessToken(ExecutableClient executableClient) {
        try {

            //executableClient保证单例
            PostClient intelligentGetClient = executableClient.newPostClient("/gettoken.json");
            OapiGettokenJsonRequest oapiGettokenJsonRequest = new OapiGettokenJsonRequest();
            //应用的唯一标识key
            oapiGettokenJsonRequest.setAppkey(APP_KEY);
            //应用的密钥
            oapiGettokenJsonRequest.setAppsecret(APP_SECRET);
            log.info("【浙政钉对接】- 获取access_token");
            //获取结果
            String apiResult = intelligentGetClient.post();

            log.info("【浙政钉对接】- 获取access_token结果：{}", apiResult);
            Type type = new TypeToken<ZheJiangTokenApiResult<ZheJiangTokenBaseApiResult>>() {
            }.getType();
            ZheJiangTokenApiResult<ZheJiangTokenBaseApiResult> tokenApiResult = GsonUtil.stringToBean(apiResult, type);
            if (tokenApiResult.success()) {
                ZheJiangTokenBaseApiResult.ZheJiangTokenApiResult resultData = tokenApiResult.getContent().getData();
                String accessToken = resultData.getAccessToken();
                log.info("【浙政钉对接】- 获取access_token成功：{}", accessToken);
                return accessToken;
            }
            log.info("【浙政钉对接】- 获取access_token失败：{}", tokenApiResult.getBizErrorCode());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Value("${dingQr.DOMAIN_NAME}")
    private String domainName;

    @Value("${dingQr.APP_KEY}")
    private String APP_KEY;

    @Value("${dingQr.APP_SECRET}")
    private String APP_SECRET;

    @Value("${dingQr.PROTOCAL}")
    private String PROTOCAL;//协议

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
